<template>
  <div class="table-list w-full h-full">
    <el-table
      ref="tableRef"
      border
      id="out-table"
      :data="tableData"
      :fit="true"
      table-layout="fixed"
      height="230"
      header-align="center"
      align="center"
      style="width:100%;"
      :header-cell-style="{
        color: '#1e293b',
        textAlign: 'center',
        fontWeight: '600',
        background: 'linear-gradient(to bottom, #f8fafc, #f1f5f9)',
        borderColor: '#e2e8f0',
        height: '40px'
      }"
      :cell-style="{
        textAlign: 'center',
        color: '#334155',
        borderColor: '#e2e8f0',
        background: '#fff',
        height: '40px'
      }"
      :row-class-name="tableRowClassName"
    >
      <el-table-column prop="docDate" :label="$t('agv.date')" align="center"/>
      <el-table-column prop="userName" :label="$t('common.operator')" align="center"/>
      <el-table-column prop="direction" :label="$t('common.direction')" width="150px" align="center">
        <template #default="scope">
          <div>
            <el-tag type="warning">
              {{ scope.row.direction.split('➱')[0] }}
            </el-tag>
            ➱
            <el-tag type="success">
              {{ scope.row.direction.split('➱')[1] }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="materialCode" :label="$t('agv.materialCode')" align="center"/>
      <el-table-column prop="qty" :label="$t('agv.qty')" align="center">
        <template #default="scope">
          <el-tag>{{ scope.row.qty }}</el-tag>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { getRealtimeTransferDetails } from '@/api/transferQuantityApi'

const tableRef = ref(null)
const tableData = ref([])
let timer = null
let scrollTimer = null
const REFRESH_INTERVAL = 30000
const SCROLL_INTERVAL = 40
const SCROLL_STEP = 1
const PAUSE_TIME = 2000 // 底部暂停时间2秒

const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 1 ? 'bg-gray-50' : ''
}

const getNumList = async () => {
  try {
    const res = await getRealtimeTransferDetails()
    tableData.value = res.data
    console.log('表格数据条数:', tableData.value.length)

    if(timer) clearInterval(timer)
    timer = setInterval(() => {
      getNumList()
    }, tableData.value.length > 8 ? 5000 : REFRESH_INTERVAL)

    if(tableData.value.length > 8) {
      await nextTick()
      startScroll()
    } else {
      if(scrollTimer) clearInterval(scrollTimer)
    }
  } catch (e) {
    console.log(e)
  }
}

// 自动滚动效果
const startScroll = () => {
  if(scrollTimer) clearInterval(scrollTimer)

  const bodyWrapper = tableRef.value.$el.querySelector('.el-scrollbar__wrap')
  if(!bodyWrapper) {
    console.log('未找到滚动容器')
    return
  }

  console.log('开始滚动，容器高度:', bodyWrapper.clientHeight)
  console.log('内容高度:', bodyWrapper.scrollHeight)

  let isPaused = false

  scrollTimer = setInterval(() => {
    if(tableData.value.length <= 8) {
      console.log('数据量不足，停止滚动')
      clearInterval(scrollTimer)
      return
    }

    if(isPaused) return

    const currentScroll = bodyWrapper.scrollTop
    const maxScroll = bodyWrapper.scrollHeight - bodyWrapper.clientHeight

    if(currentScroll >= maxScroll) {
      console.log('滚动到底部，暂停2秒')
      isPaused = true
      setTimeout(() => {
        bodyWrapper.scrollTop = 0
        isPaused = false
      }, PAUSE_TIME)
    } else {
      bodyWrapper.scrollTop = currentScroll + SCROLL_STEP
    }
  }, SCROLL_INTERVAL)
}

onMounted(() => {
  getNumList()
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
  if (scrollTimer) clearInterval(scrollTimer)
})
</script>

<style scoped lang="scss">
.table-list {
  height: 100%;
  overflow: hidden;

  :deep(.el-table) {
    height: 100%;

    // 表格hover效果
    tbody tr:hover > td {
      background-color: #f8fafc !important;
    }

    // 斑马纹样式
    .bg-gray-50 td {
      background-color: #f8fafc;
    }

    // 单元格过渡动画
    td {
      transition: background-color 0.2s ease;
    }

    // 表格边框
    --el-table-border-color: #e2e8f0;

    // 去除表格底部边框
    &::before {
      display: none;
    }

    // 滚动容器样式
    .el-scrollbar__wrap {
      overflow-y: auto !important;

      &::-webkit-scrollbar {
        width: 0;
        height: 0;
      }
    }

    // 确保表格头部固定
    .el-table__header-wrapper {
      position: sticky;
      top: 0;
      z-index: 1;
    }
  }
}
</style>
